﻿using System;  
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.JScript.Vsa;
using Microsoft.JScript;
using System.CodeDom.Compiler;
using System.Reflection;

namespace RuntimeHelloWorlds
{
	public class JScriptDotNetHelloWorld
	{

		private static readonly string _jscriptSource =

			 @"
			import System;

			package Dynamic
			{
			   public class Evaluator
			   {
				  public function Eval(expr : String) : String 
				  { 
					 return eval(expr); 
				  }

				  public function Print(text : String)
				  {
					Console.WriteLine(text);
				  }
			   }
			}";

		// I realize this is an odd way to do it:
		public void SayHelloWorld()
		{
			var codeDomProvider = JScriptCodeProvider.CreateProvider("JScript");
			var parameters = new CompilerParameters();
			parameters.GenerateInMemory = true;
			var results = codeDomProvider.CompileAssemblyFromSource(parameters, _jscriptSource);

			var type = results.CompiledAssembly.GetType("Dynamic.Evaluator");

			dynamic instance = Activator.CreateInstance(type);

			instance.Print(instance.Eval(@"new Array('Hello, World!', '(JScript.NET)').join(' ')"));
		}
	}
}
